import React, { useEffect, useMemo, useState } from 'react';
import Base from './base';
import aopc from 'aopc';
import { Common } from 'UtilsCommon';

const _PageConfigs = {};

const getConfig = (property, pageAxis, setConfig) => {
    const id = property.pageId;
    const isPreview = window.location.href.indexOf("preview.html") > 0;
    const pathQuery = isPreview ? `/getconfig?id=${id}` : `/${property.pageName}.json`;
    pageAxis.dispatchAction("WebService", "getConfig", { pathQuery }).then(res => {
        res.isDiv = false;
        _PageConfigs[id] = res;
        setConfig(res);
    });
};

export default React.memo((props) => {
    const { property, pageId, pageAxis } = Base.getProps(props);

    const [config, setConfig] = useState(property.isOnlyLayout ? null : _PageConfigs[property.pageId]);

    useEffect(() => {
        if (!config && property.isOnlyLayout) getConfig(property, pageAxis, setConfig);
    }, [property, pageAxis, config, setConfig]);

    if (property.isOnlyLayout) {
        if (!config || config.properties.length === 0) return null;

        property.properties = Common.clone(config.properties);
        property.expandInit && property.expandInit();
        return Base.renderProperties(property, pageId);
    }

    const page = aopc.componentPages[property.pageId];
    if (!page) return null;

    const isPreview = window.location.href.indexOf("preview.html") > 0;

    const props2 = useMemo(() => ({
        ...pageAxis.props,
        property,
        id: isPreview ? property.pageId : '',
        isComponentPage: true,
        getPageAxis: () => pageAxis,
        key: property.id + property.pageId
    }), [property, pageAxis]);

    return React.createElement(page.component, props2);
});